package com.xin.chaingeneration.controller;

import com.xin.chaingeneration.common.ResponseEntity;
import com.xin.chaingeneration.entity.ProductType;
import com.xin.chaingeneration.service.ProductTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/productType")
public class ProductTypeController {

    @Autowired
    ProductTypeService productTypeService;

    @PostMapping("/create")
    public ResponseEntity create(@RequestBody ProductType productType) {
        log.info(productType.toString());

        // 检查数据库中是否已存在具有相同 typeName 的 ProductType
        boolean exists = productTypeService.existsByTypeName(productType.getTypeName());
        if (exists) {
            // 如果已存在，返回一个错误响应
            return ResponseEntity.success("已存在");
        } else {
            // 如果不存在，保存新的 ProductType
            productTypeService.saveOrUpdate(productType);

            // 创建响应实体
            ResponseEntity<ProductType> responseEntity = new ResponseEntity().success(productType);
            responseEntity.setCode(1);
            responseEntity.setMsg("创建成功");

            return responseEntity;
        }
    }

    @GetMapping("/getTypes")
    public ResponseEntity getTypes(){

        List<ProductType> list = productTypeService.list();

        List<String> types = new ArrayList<>();

        for (ProductType p : list){
            types.add(p.getTypeName());
        }

        ResponseEntity<List<String>> responseEntity = new ResponseEntity<>();
        responseEntity.setData(types);
        responseEntity.setCode(1);

        return responseEntity;
    }
}
